/**
 * Created by Merdan on 2017/2/13.
 */
adminApp.controller('MenuCtrl', ['$scope', '$location', '$menuItems', '$rootScope',
    function ($scope, $location, $menuItems, $rootScope) {
        $scope.isActive = function (route) {
            if ($location.path().indexOf(route) === 0) {
                return true;
            }
            return route === $location.path();
        };
        // Menu Items
        var $sidebarMenuItems = $menuItems.instantiate();
        $sidebarMenuItems.prepareSidebarMenu = function () {
            this.addHeader('菜单');
            var blog	= this.addItem('用户管理', 			'/users', 			'glyphicon glyphicon-user');
            var canteen = this.addItem('餐厅管理', 			'/canteens', 		'glyphicon glyphicon-modal-window');
            var sku		= this.addItem('物料管理', 			'/product', 		'glyphicon glyphicon-barcode');

            sku.addItem('物料列表', 	'/product');
            sku.addItem('物料分类', 	'./category');
            // dashboard.addItem('Update Hightlights', '/app/update-highlights').setLabel('v1.3', 'pink');
            return this;
        };

        $scope.menuItems = $sidebarMenuItems.prepareSidebarMenu().getAll();

        // Set Active Menu Item
        $sidebarMenuItems.setActive( $location.path());

        $rootScope.$on('$locationChangeSuccess', function()
        {
            $sidebarMenuItems.setActive($location.path());
        });
    }]);
//user list
adminApp.controller('UserListCtrl', ['$routeParams', '$scope', '$location', 'User', 'NgTableParams', 'SweetAlert', 'ngDialog', 'TEMPLATE', function($routeParams, $scope, $location, User, NgTableParams, SweetAlert, ngDialog, TEMPLATE) {

    $scope.filters = {
        email: ""
    };
    var firstLoad = true;
    $scope.userTable = new NgTableParams(
        angular.extend(
            {
                page: 1, // show first page
                count: 20, // count per page
                filter: $scope.filters
            },
            $location.search())
        , {
            counts: [20, 50, 100],
            paginationMaxBlocks: 8,
            total: 0,
            getData: function($defer, params) {
                User.get(params.url(), function(data) {
                    if (data.result) {
                        if (!firstLoad) {
                            $location.searchReplace(params.url());
                        }
                        firstLoad = false;
                        params.total(data.data.total);
                        $defer.resolve(data.data.data);
                    } else {
                        SweetAlert.swal('', data.message, "error");
                    }
                }, function(error) {
                    $scope.saveLoading = false;
                    if (error.status === 401) {
                        SweetAlert.swal('', lang.no_permistion, "error");
                        $location.path("/address");
                    }
                });
            }
        });

    $scope.openDialog = function(user) {
        var _dialog = ngDialog.open({
            template: TEMPLATE + 'user/edit.html',
            controller: 'UserEditCtrl',
            data: user

        });
        _dialog.closePromise.then(function(data) {
            if (data.value === "ngDialogAfterCreate") {
                $scope.userTable.reload();
            }
        });
    }

}]);
//show user info
adminApp.controller('UserEditCtrl', ['$scope', '$location', '$routeParams', 'User', 'SweetAlert',

    function($scope, $location, $routeParams, User, SweetAlert) {
        $scope.saveLoading = false;
        $scope.error = {};
        $scope.loading = true;
        $scope.new = false;
        $scope.user = $.extend({}, true, $scope.ngDialogData);
        if (Object.keys($scope.user).length === 0) {
            $scope.new = true;
            $scope.user.type = 0;
        }

        $scope.submit = function() {
            $scope.saveLoading = true;
            var user = new User($scope.user);
            if ($scope.new) {
                user.$save({}, function(rs, header, status) {
                    $scope.saveLoading = false;
                    if (rs.result) {
                        $scope.closeThisDialog('ngDialogAfterCreate');
                        SweetAlert.swal({
                            title: '',
                            text: rs.message,
                            timer: timer_value,
                            showConfirmButton: false,
                            type: "success"
                        });
                        $scope.userTable.reload();
                    } else {
                        SweetAlert.swal('', rs.message, "error");
                    }
                }, function(error) {
                    $scope.saveLoading = false;
                    if (error.status === 422) {
                        $scope.error = error.data;
                        return;
                    }
                    SweetAlert.swal('', lang.unknown, "error");
                });
            } else {
                user.$update({
                    id: $scope.user.id
                }, function(rs, header, status) {
                    $scope.saveLoading = false;
                    if (rs.result) {
                        $scope.closeThisDialog('ngDialogAfterCreate');
                        SweetAlert.swal({
                            title: '',
                            text: rs.message,
                            timer: timer_value,
                            showConfirmButton: false,
                            type: "success"
                        });
                        if (user.role === 'admin') {
                            $location.path("/user");
                        }

                    } else {
                        SweetAlert.swal('', rs.message, "error");
                    }
                }, function(error) {
                    $scope.saveLoading = false;
                    if (error.status === 401) {
                        $location.path("/address");
                    }
                    if (error.status === 422) {
                        $scope.error = error.data;
                        return;
                    }
                    SweetAlert.swal('', lang.unknown, "error");
                });
            }

        }
    }]);
//canteen list
adminApp.controller('CanteenListCtrl', ['$routeParams', '$scope', '$location', 'Canteen', 'NgTableParams', 'SweetAlert', 'ngDialog', 'TEMPLATE', function($routeParams, $scope, $location, Canteen, NgTableParams, SweetAlert, ngDialog, TEMPLATE) {

    $scope.filters = {
        email: ""
    };
    var firstLoad = true;
    $scope.canteenTable = new NgTableParams(
        angular.extend(
            {
                page: 1, // show first page
                count: 20, // count per page
                filter: $scope.filters
            },
            $location.search())
        , {
            counts: [20, 50, 100],
            paginationMaxBlocks: 8,
            total: 0,
            getData: function($defer, params) {
                Canteen.get(params.url(), function(data) {
                    if (data.result) {
                        if (!firstLoad) {
                            $location.searchReplace(params.url());
                        }
                        firstLoad = false;
                        params.total(data.data.total);
                        $defer.resolve(data.data.data);
                    } else {
                        SweetAlert.swal('', data.message, "error");
                    }
                }, function(error) {
                    $scope.saveLoading = false;
                    if (error.status === 401) {
                        SweetAlert.swal('', lang.no_permistion, "error");
                        $location.path("/address");
                    }
                });
            }
        });

    $scope.openDialog = function(canteen) {
        var _dialog = ngDialog.open({
            template: TEMPLATE + 'canteen/edit.html',
            controller: 'CanteenEditCtrl',
            data: canteen

        });
        _dialog.closePromise.then(function(data) {
            if (data.value === "ngDialogAfterCreate") {
                $scope.canteenTable.reload();
            }
        });
    }

}]);
//show canteen info
adminApp.controller('CanteenEditCtrl', ['$scope', '$location', '$routeParams', 'Canteen', 'SweetAlert', '$http', 'DASHBOARD_API', 'ngDialog', 'TEMPLATE', function($scope, $location, $routeParams, Canteen, SweetAlert, $http, DASHBOARD_API, ngDialog, TEMPLATE) {
    $scope.saveLoading = false;
    $scope.error = {};
    $scope.loading = true;
    $scope.new = false;
    $scope.canteen = $.extend({}, true, $scope.ngDialogData);
    if (Object.keys($scope.canteen).length === 0) {
        $scope.new = true;
        $scope.canteen.type = 0;
    }

    function getManagers() {
        $http.get(DASHBOARD_API + '/user/managers')
            .success(function (data) {
                if (data.result) {
                    data.data.unshift({
                        name : '请选择库存管理员'
                    });
                    $scope.users = data.data;
                } else {
                    SweetAlert.swal('', data.message, "error");
                }
            })
            .error(function (error) {
                SweetAlert.swal('', lang.unknown, "error");
            })
    }
    getManagers();

    $scope.addManager = function() {
        var _dialog = ngDialog.open({
            template: TEMPLATE + 'user/edit.html',
            controller: 'UserEditCtrl'
        });
        _dialog.closePromise.then(function(data) {
            if (data.value === "ngDialogAfterCreate") {
                getManagers();
            }
        });
    };

    $scope.submit = function() {
        $scope.saveLoading = true;
        var canteen = new Canteen($scope.canteen);
        if ($scope.new) {
            canteen.$save({}, function(rs, header, status) {
                $scope.saveLoading = false;
                if (rs.result) {
                    $scope.closeThisDialog('ngDialogAfterCreate');
                    SweetAlert.swal({
                        title: '',
                        text: rs.message,
                        timer: timer_value,
                        showConfirmButton: false,
                        type: "success"
                    });
                    $scope.canteenTable.reload();
                } else {
                    SweetAlert.swal('', rs.message, "error");
                }
            }, function(error) {
                $scope.saveLoading = false;
                if (error.status === 422) {
                    $scope.error = error.data;
                    return;
                }
                SweetAlert.swal('', lang.unknown, "error");
            });
        } else {
            canteen.$update({
                id: $scope.canteen.id
            }, function(rs, header, status) {
                $scope.saveLoading = false;
                if (rs.result) {
                    $scope.closeThisDialog('ngDialogAfterCreate');
                    SweetAlert.swal({
                        title: '',
                        text: rs.message,
                        timer: timer_value,
                        showConfirmButton: false,
                        type: "success"
                    });
                    if (canteen.role === 'admin') {
                        $location.path("/canteen");
                    }

                } else {
                    SweetAlert.swal('', rs.message, "error");
                }
            }, function(error) {
                $scope.saveLoading = false;
                if (error.status === 401) {
                    $location.path("/address");
                }
                if (error.status === 422) {
                    $scope.error = error.data;
                    return;
                }
                SweetAlert.swal('', lang.unknown, "error");
            });
        }

    }
}]);
// product category
adminApp.controller('CategoryListCtrl', ['$routeParams', '$scope', 'Category', 'NgTableParams', 'SweetAlert',
    function ($routeParams, $scope, Category, NgTableParams, SweetAlert) {

        var self = this;

        var originalData = [];
        $scope.saveLoading = false;
        $scope.error = {};
        $scope.category = {
            ug_name: '',
            zh_name: ''
        };
        $scope.tableParams = new NgTableParams({
            page: 1,            // show first page
            count: 10          // count per page
        }, {
            counts: [],
            paginationMaxBlocks: 8,
            total: 0,

            getData: function ($defer, params) {
                Category.get(params.url(), function (data) {
                    if (data.result) {
                        params.total(data.data.total);
                        $defer.resolve(data.data.data);
                        originalData = angular.copy(data.data.data);
                    } else {
                        SweetAlert.swal('', data.message, "error");
                    }
                });
            }
        });

        $scope.addCategory = function (category) {
            $scope.saveLoading = true;

            var categoryObj = new Category(category);
            categoryObj.$save({}, function (rs, header, status) {
                $scope.saveLoading = false;
                if (rs.result) {
                    SweetAlert.swal({
                        title: '',
                        text: rs.message,
                        timer: timer_value,
                        showConfirmButton: false,
                        type: "success"
                    });
                    $scope.tableParams.reload();
                    $scope.category = {};
                } else {
                    SweetAlert.swal('', rs.message, "error");
                }
            }, function (error) {
                $scope.saveLoading = false;
                if (error.status === 422) {
                    $scope.error = error.data;
                    return;
                }
                SweetAlert.swal('', lang.unknown, "error");
            });
        };


        $scope.cancelEdit = function (row, rowForm) {
            var originalRow = resetRow(row, rowForm);
            angular.extend(row, originalRow);
        };

        $scope.saveCategory = function (category, rowForm) {
            $scope.saveLoading = true;
            var categoryObj = new Category(category);
            categoryObj.$update({
                id: category.id
            }, function (rs, header, status) {
                $scope.saveLoading = false;
                if (rs.result) {
                    var originalRow = resetRow(category, rowForm);
                    angular.extend(originalRow, category);
                    SweetAlert.swal({
                        title: '',
                        text: rs.message,
                        timer: timer_value,
                        showConfirmButton: false,
                        type: "success"
                    });
                } else {
                    SweetAlert.swal('', rs.message, "error");
                }
            }, function (error) {
                $scope.saveLoading = false;
                if (error.status === 422) {
                    $scope.error = error.data;
                    return;
                }
                $scope.closeThisDialog();
                SweetAlert.swal('', lang.unknown, "error");
            });
        };

        function resetRow(row, rowForm) {
            row.isEditing = false;
            rowForm.$setPristine();
            self.tableTracker.untrack(row);
            console.log('rowForm', rowForm);
            console.log('row.id', row.id);

            var originalRow;

            originalData.map(function (item) {
                if (item.id === row.id) {
                    originalRow = item;
                }
            });

            return originalRow;
        }

        //remove news
        $scope.removeConfirm = function (id, index) {
            SweetAlert.swal({
                    title: '',
                    text: lang.delete_warning,
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonClass: "btn-danger",
                    confirmButtonText: lang.yes,
                    cancelButtonText: lang.no,
                    closeOnConfirm: false,
                    closeOnCancel: true,
                    showLoaderOnConfirm: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        $scope.remove(id, index);
                    }
                });
        };

        //remove method
        $scope.remove = function (id, index) {
            Category.remove({id: id}, function (rs) {
                if (rs.result) {
                    SweetAlert.swal({
                        title: "",
                        text: rs.message,
                        timer: timer_value,
                        showConfirmButton: false,
                        type: "success"
                    });
                    $scope.tableParams.data.splice(index, 1);
                    if ($scope.tableParams.data.length < 1) {
                        $scope.tableParams.reload();
                    }
                } else {
                    SweetAlert.swal('', rs.message, "error");
                }
            });
        };

    }]);

// product
adminApp.controller('ProductListCtrl', ['$routeParams', '$scope', 'Product', 'NgTableParams', 'SweetAlert', '$location', '$http', 'DASHBOARD_API', 'ngDialog', 'TEMPLATE', function ($routeParams, $scope, Product, NgTableParams, SweetAlert, $location, $http, DASHBOARD_API, ngDialog, TEMPLATE) {

    var self = this;
    self.originalData = [];

    $scope.filters = {
        ug_name: '',
        category_id : ''
    };
    $scope.error = {
        images : ""
    };

    $scope.categories = [];

    $scope.editProduct = function (sku, rowForm){
        sku.isEditing = true;
    };

    $scope.cancelEdit = function(row, rowForm) {
        var originalRow = resetRow(row, rowForm);
        angular.extend(row, originalRow);
        $scope.error = {};
    };

    function resetRow(row, rowForm){
        row.isEditing = false;
        rowForm.$setPristine();

        var originalRow = {};

        self.originalData.map(function(item){
            if(item.id === row.id){
                originalRow = item;
            }
        });

        return originalRow;
    }

    $scope.saveProduct = function (sku, rowForm) {
        $scope.saveLoading = true;
        var skuObj = new Product(sku);

        skuObj.$update({id: sku.id}, function (rs, header, status) {
            $scope.saveLoading = false;
            if (rs.result) {
                var originalRow = resetRow(sku, rowForm);
                angular.extend(originalRow, sku);
                SweetAlert.swal({
                    title: '',
                    text: rs.message,
                    timer: timer_value,
                    showConfirmButton: false,
                    type: "success"
                });
                sku.isEditing = false;
            } else {
                SweetAlert.swal('', rs.message, "error");
            }
        }, function (error) {
            $scope.saveLoading = false;
            if (error.status === 422) {
                $scope.error = error.data;
                return;
            }
            SweetAlert.swal('', lang.unknown, "error");
        });
    };

    $http.get(DASHBOARD_API + '/product/categories', {})
        .success(function (rs) {
            if (rs.result) {
                $scope.categories = rs.data;
                $scope.categories.unshift({
                    name : "请选择",
                    id: ""
                });
            } else {
                SweetAlert.swal('', rs.message, "error");
                $location.path("/category");
            }
        })
        .error(function (rs) {
            SweetAlert.swal('', lang.unknown, "error");
            $location.path("/category");
        });

    var firstLoad = true;
    $scope.productTable = new NgTableParams(
        angular.extend(
            {
                page: 1,
                count: 20,
                filter: $scope.filters
            },
            $location.search()), {
            counts: [20, 50, 100],
            paginationMaxBlocks: 8,
            total: 0,
            getData: function ($defer, params) {
                Product.get(params.url(), function (data) {
                    if (data.result) {
                        if (!firstLoad) {
                            $location.searchReplace(params.url());
                        }
                        firstLoad = false;
                        self.originalData = angular.copy(data.data.data);
                        params.total(data.data.total);
                        $defer.resolve(data.data.data);
                    } else {
                        SweetAlert.swal('', data.message, "error");
                    }
                });
            }
        });

    $scope.openDialog = function() {
        var _dialog = ngDialog.open({
            template: TEMPLATE + 'product/edit.html',
            controller: 'ProductCtrl',
            data: $scope.categories

        });
        _dialog.closePromise.then(function(data) {
            if (data.value === "ngDialogAfterCreate") {
                $scope.productTable.reload();
            }
        });
    };

    $scope.$on('ngTableAfterReloadData', function () {
        console.log('table changed', $scope.productTable);
    });
}]);

adminApp.controller('ProductCtrl', ['$scope', '$location', '$routeParams', 'Product', 'SweetAlert',
    function($scope, $location, $routeParams, Product, SweetAlert) {
        $scope.saveLoading = false;
        $scope.error = {};
        $scope.loading = true;
        $scope.new = false;
        $scope.categories = $.extend({}, true, $scope.ngDialogData);
        console.log('$scope.categories', $scope.categories);
        $scope.product = {
            category_id : ""
        };

        $scope.submit = function() {
            $scope.saveLoading = true;
            var product = new Product($scope.product);
            product.$save({}, function(rs, header, status) {
                $scope.saveLoading = false;
                if (rs.result) {
                    $scope.closeThisDialog('ngDialogAfterCreate');
                    SweetAlert.swal({
                        title: '',
                        text: rs.message,
                        timer: timer_value,
                        showConfirmButton: false,
                        type: "success"
                    });
                    $scope.productTable.reload();
                } else {
                    SweetAlert.swal('', rs.message, "error");
                }
            }, function(error) {
                $scope.saveLoading = false;
                if (error.status === 422) {
                    $scope.error = error.data;
                    return;
                }
                SweetAlert.swal('', lang.unknown, "error");
            });
        }
    }]);